package com.shiikong_memory.yez.Tool;

import io.micrometer.common.util.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 复制resource文件、文件夹
 */
public class FreeMarkerUtil {

    /**
     * 复制path目录下所有文件，覆盖（jar）
     *
     * @param path    文件目录 不能以/开头
     * @param newPath 新文件目录
     */
    public static void copyFolderFromJarCover(String path, String newPath) throws IOException {
        if (!new File(newPath).exists()) {
            new File(newPath).mkdir();
        }
        if (path.contains("\\")) {
            path = path.replace("\\", "/");
        }
        if (path.startsWith("/")) {
            //以/开头，去掉/
            path = path.substring(1);
        }
        if (path.endsWith("/")) {
            //以/结尾，去掉/
            path = path.substring(0, path.length() - 1);
        }

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //获取所有匹配的文件（包含根目录文件、子目录、子目录下的文件）
        Resource[] resources = resolver.getResources("classpath:" + path + "/**/");
        //打印有多少文件
        for (Resource resource : resources) {
            //文件名
            String filename = resource.getFilename();

            //以jar包运行时，不能使用resource.getFile()获取文件路径、判断是否为文件等，会报错：
            //java.io.FileNotFoundException: class path resource [xxx/xxx/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx.jar!/BOOT-INF/classes!/xxx/xxx

            //文件路径
            //file [/xxx/xxx]
            String description = resource.getDescription();
            description = description.replace("\\", "/");
            //保留 /xxx/xxx
            description = description.replaceAll("(.*\\[)|(]$)", "").trim();

            //以“文件目录”进行分割，获取文件相对路径
            String[] descriptions = description.split(path + "/");
            if (descriptions.length > 1) {
                //获取文件相对路径，/xxx/xxx
                String relativePath = descriptions[1];

                //新文件路径
                String newFilePath = newPath + "/" + relativePath;
                if (FreeMarkerUtil.isDirectory(filename)) {
                    //文件夹
                    if (!new File(newFilePath).exists()) {
                        new File(newFilePath).mkdir();
                    }

                } else {

                    //文件
                    InputStream stream = resource.getInputStream();
                    write2File(stream, newFilePath);
                }
            }
        }
    }

    /**
     * 复制path目录下所有文件，不覆盖（jar）
     *
     * @param path    文件目录 不能以/开头
     * @param newPath 新文件目录
     */
    public static void copyFolderFromJar(String path, String newPath) throws IOException {
        if (!new File(newPath).exists()) {
            new File(newPath).mkdir();
        }
        if (path.contains("\\")) {
            path = path.replace("\\", "/");
        }
        if (path.startsWith("/")) {
            //以/开头，去掉/
            path = path.substring(1);
        }
        if (path.endsWith("/")) {
            //以/结尾，去掉/
            path = path.substring(0, path.length() - 1);
        }

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //获取所有匹配的文件（包含根目录文件、子目录、子目录下的文件）
        Resource[] resources = resolver.getResources("classpath:" + path + "/**/");
        //打印有多少文件
        for (Resource resource : resources) {
            //文件名
            String filename = resource.getFilename();

            //以jar包运行时，不能使用resource.getFile()获取文件路径、判断是否为文件等，会报错：
            //java.io.FileNotFoundException: class path resource [xxx/xxx/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx.jar!/BOOT-INF/classes!/xxx/xxx

            //文件路径
            //file [/xxx/xxx]
            String description = resource.getDescription();
            description = description.replace("\\", "/");
            //保留 /xxx/xxx
            description = description.replaceAll("(.*\\[)|(]$)", "").trim();

            //以“文件目录”进行分割，获取文件相对路径
            String[] descriptions = description.split(path + "/");
            if (descriptions.length > 1) {
                //获取文件相对路径，/xxx/xxx
                String relativePath = descriptions[1];

                //新文件路径
                String newFilePath = newPath + "/" + relativePath;
                if (FreeMarkerUtil.isDirectory(filename)) {
                    //文件夹
                    if (!new File(newFilePath).exists()) {
                        new File(newFilePath).mkdir();
                    }

                } else {

                    //文件
                    File f = new File(newFilePath);
                    if (!f.exists()) {
                        InputStream stream = resource.getInputStream();
                        write2File(stream, newFilePath);
                    }
                }
            }
        }
    }

    /**
     * 复制文件（jar）
     *
     * @param path    源文件路径
     * @param newPath 新文件路径
     */
    public static void copyFileFromJar(String path, String newPath) throws IOException {
        //不读文件路径，直接读取文件流
        InputStream inputStream = ClassUtils
                .getDefaultClassLoader()
                .getResourceAsStream(path);
        write2File(inputStream, newPath);
    }

    /**
     * 输入流写入文件
     *
     * @param is       输入流
     * @param filePath 文件保存目录路径
     * @throws IOException IOException
     */
    public static void write2File(InputStream is, String filePath) throws IOException {
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        OutputStream os = new FileOutputStream(destFile);
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((len = is.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
    }

    /**
     * 判断是否为目录、文件夹
     * @param filename 文件名
     * @return boolean
     */
    public static boolean isDirectory(String filename) {
        if (StringUtils.isBlank(filename)) {
            return false;
        }

        //有后缀，是文件
        boolean contains = filename.contains(".");
        if (contains) {
            return false;
        }

        //是文件夹
        return true;
    }

    /**
     * 判断是否为目录、文件夹
     * @param path 文件路径
     * @return boolean
     */
    public static boolean isDirectoryFromPath(String path) {
        if (StringUtils.isBlank(path)) {
            return false;
        }

        String newPath = path.replace("\\", "/");
        if (newPath.contains("/")) {
            newPath = newPath.substring(newPath.lastIndexOf("/"));
        }

        //有后缀，是文件；
        boolean contains = newPath.contains(".");
        if (contains) {
            return false;
        }

        //是文件夹
        return true;
    }

    public static void main(String[] args) throws IOException {
        //文件夹复制
        String path = "templates";
        String newPath = "D:/tmp";
        FreeMarkerUtil.copyFolderFromJarCover(path, newPath);

        //文件复制
        String filePath = "application.properties";
        String newFilePath = "D:/tmp/application.properties";
        FreeMarkerUtil.copyFileFromJar(filePath, newFilePath);
    }

}
